package com.ruoyi.common.utils.file;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;

public class JsonToExcelConverter {

    public static void convertJsonToExcel(String jsonArrayString, String outputPath) {
        try (Workbook workbook = new XSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream(outputPath)) {
            Sheet sheet = workbook.createSheet("Data");

            ObjectMapper mapper = new ObjectMapper();
            List<Map<String, Object>> dataList = mapper.readValue(jsonArrayString, new TypeReference<List<Map<String, Object>>>() {});

            Set<String> columns = new HashSet<>();
            dataList.forEach(map -> columns.addAll(map.keySet()));

            // Create header row
            Row headerRow = sheet.createRow(0);
            int headerCellNum = 0;
            for (String key : columns) {
                Cell cell = headerRow.createCell(headerCellNum++);
                cell.setCellValue(key);
            }

            int rowNum = 1;
            for (Map<String, Object> data : dataList) {
                Row row = sheet.createRow(rowNum++);
                int cellNum = 0;
                for (String key : columns) {
                    Cell cell = row.createCell(cellNum++);
                    Object value = data.get(key);
                    if (value instanceof Number) {
                        cell.setCellValue(((Number) value).doubleValue());
                    } else if (value != null) {
                        cell.setCellValue(value.toString());
                    } else {
                        cell.setCellValue("");
                    }
                }
            }

            // Auto-size columns
            for (int i = 0; i < columns.size(); i++) {
                sheet.autoSizeColumn(i);
            }

            // Write the workbook to the file system
            workbook.write(fileOut);
        } catch (IOException e) {
            System.err.println("Error during Excel file creation: " + e.getMessage());
        }
    }

//    public static void main(String[] args) {
//        String json = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Anna\", \"age\":25, \"city\":\"San Francisco\"}, {\"name\":\"Steve\", \"profession\":\"Developer\"}]";
//        convertJsonToExcel(json, "output.xlsx");
//    }
}
